<template>
  <view class="notification-container">
    <!-- 通知图标 -->
    <view class="notification-icon" @click="toggleNotificationList">
      <uni-icons type="chat" size="24" color="#333"></uni-icons>
      <!-- 消息数量徽章 -->
      <view v-if="unreadCount > 0" class="badge">
        <text class="badge-text">{{ unreadCount > 99 ? '99+' : unreadCount }}</text>
      </view>
    </view>

    <!-- 通知列表弹窗 -->
    <view v-if="showNotificationList" class="notification-overlay" @click="hideNotificationList">
      <view class="notification-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">消息通知</text>
          <view class="popup-close" @click="hideNotificationList">
            <uni-icons type="close" size="20" color="#999"></uni-icons>
          </view>
        </view>
        
        <scroll-view 
          class="popup-content" 
          scroll-y 
          @scrolltolower="loadMoreMessages"
          :refresher-enabled="true"
          :refresher-triggered="refreshing"
          @refresherrefresh="onRefresh"
        >
          <!-- 消息列表 -->
          <view v-if="notificationList.length > 0" class="message-list">
            <view 
              v-for="message in notificationList" 
              :key="message.id" 
              class="message-item"
              @click="handleMessageClick(message)"
            >
              <view class="message-avatar">
                <text class="avatar-text">{{ message.title.charAt(0) }}</text>
              </view>
              <view class="message-content">
                <view class="message-header">
                  <text class="message-title">{{ message.title }}</text>
                  <text class="message-time">{{ message.time }}</text>
                </view>
                <text class="message-preview">{{ message.preview }}</text>
              </view>
              <view v-if="!message.isRead" class="unread-dot"></view>
            </view>
          </view>
          
          <!-- 空状态 -->
          <view v-else class="empty-state">
            <text class="empty-text">暂无消息</text>
          </view>
          
          <!-- 加载更多提示 -->
          <view v-if="loadingMore" class="loading-more">
            <text>加载中...</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'NotificationBadge',
  data() {
    return {
      showNotificationList: false,
      unreadCount: 5,
      notificationList: [],
      page: 1,
      pageSize: 10,
      hasMore: true,
      loadingMore: false,
      refreshing: false
    }
  },
  mounted() {
    this.loadUnreadCount();
  },
  methods: {
    // 切换通知列表显示
    toggleNotificationList() {
      this.showNotificationList = !this.showNotificationList;
      if (this.showNotificationList) {
        this.loadNotifications();
      }
    },
    
    // 隐藏通知列表
    hideNotificationList() {
      this.showNotificationList = false;
    },
    
    // 加载未读消息数量
    loadUnreadCount() {
      const userId = uni.getStorageSync('userId') || 22;
      uni.request({
        url: 'http://localhost:9003/message/getUnreadCount',
        data: {
          toUser: userId
        },
        success: (res) => {
          if (res.statusCode === 200) {
            this.unreadCount = res.data || 0;
          }
        },
        fail: (err) => {
          console.error('获取未读消息数量失败', err);
        }
      });
    },
    
    // 加载通知数据
    loadNotifications() {
      const userId = uni.getStorageSync('userId') || 22;
      uni.request({
        url: 'http://localhost:9003/message/getNoMessage',
        data: {
          toUser: 22,
          page: this.page,
          pageSize: this.pageSize
        },
        success: (res) => {
          if (res.statusCode === 200) {
            const data = res.data || [];
            // 格式化消息数据
            const formattedMessages = data.map(msg => ({
              id: msg.messageid,
              title: `用户${msg.fromUser}`,
              time: this.formatMessageTime(msg.sendTime),
              preview: msg.content,
              isRead: msg.isRead || false
            }));
            
            if (this.page === 1) {
              this.notificationList = formattedMessages;
            } else {
              this.notificationList = [...this.notificationList, ...formattedMessages];
            }
            
            // 判断是否还有更多数据
            this.hasMore = data.length === this.pageSize;
            
            // 更新未读数量
            this.loadUnreadCount();
          }
        },
        fail: (err) => {
          console.error('获取消息列表失败', err);
          uni.showToast({
            title: '获取消息列表失败',
            icon: 'none'
          });
        },
        complete: () => {
          this.loadingMore = false;
          this.refreshing = false;
        }
      });
    },
    
    // 格式化消息时间
    formatMessageTime(sendTime) {
      if (!sendTime) return '';
      
      const date = new Date(sendTime);
      const now = new Date();
      const diff = now.getTime() - date.getTime();
      const diffMinutes = Math.floor(diff / (1000 * 60));
      const diffHours = Math.floor(diff / (1000 * 60 * 60));
      const diffDays = Math.floor(diff / (1000 * 60 * 60 * 24));
      
      if (diffMinutes < 1) {
        return '刚刚';
      } else if (diffMinutes < 60) {
        return `${diffMinutes}分钟前`;
      } else if (diffHours < 24) {
        return `${diffHours}小时前`;
      } else if (diffDays < 7) {
        return `${diffDays}天前`;
      } else {
        return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
      }
    },
    
    // 下拉刷新
    onRefresh() {
      this.refreshing = true;
      this.page = 1;
      this.loadNotifications();
    },
    
    // 上拉加载更多
    loadMoreMessages() {
      if (!this.hasMore || this.loadingMore) return;
      
      this.loadingMore = true;
      this.page++;
      this.loadNotifications();
    },
    
    // 处理消息点击
    handleMessageClick(message) {
      // 跳转到消息详情页
      uni.navigateTo({
        url: `/pages/message-detail/message-detail?messageId=${message.id}&messageData=${encodeURIComponent(JSON.stringify(message))}`
      });
      
      this.hideNotificationList();
    }
  }
}
</script>

<style lang="scss" scoped>
.notification-container {
  position: relative;
}

.notification-icon {
  position: relative;
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.9);
  }
}

.badge {
  position: absolute;
  top: 0;
  right: 0;
  min-width: 30px;
  height: 30px;
  background: #ff3333;
  border-radius: 999rpx;
  border: 4rpx solid #fff;
  padding: 0 4rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.badge-text {
  color: white;
  font-size: 27rpx;
  line-height: 1;
}

.notification-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.notification-popup {
  background: #fff;
  border-radius: 20rpx;
  width: 640rpx;
  max-width: 90%;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.15);
  animation: slideUp 0.3s ease;
}

@keyframes slideUp {
  from { 
    opacity: 0;
    transform: translateY(60rpx) scale(0.9);
  }
  to { 
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.popup-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  
  .popup-title {
    font-size: 32rpx;
    font-weight: 600;
  }
  
  .popup-close {
    width: 40rpx;
    height: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    transition: all 0.3s ease;
    
    &:active {
      background: rgba(255, 255, 255, 0.3);
      transform: scale(0.9);
    }
  }
}

.popup-content {
  max-height: 60vh;
  overflow-y: auto;
}

.message-list {
  .message-item {
    display: flex;
    align-items: flex-start;
    padding: 30rpx;
    border-bottom: 1rpx solid #f5f5f5;
    transition: all 0.3s ease;
    position: relative;
    
    &:active {
      background: #f8f9fa;
    }
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .message-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20rpx;
    flex-shrink: 0;
    
    .avatar-text {
      color: white;
      font-size: 28rpx;
      font-weight: 600;
    }
  }
  
  .message-content {
    flex: 1;
    min-width: 0;
    
    .message-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 8rpx;
      
      .message-title {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        flex: 1;
        margin-right: 20rpx;
      }
      
      .message-time {
        font-size: 24rpx;
        color: #999;
        flex-shrink: 0;
      }
    }
    
    .message-preview {
      font-size: 26rpx;
      color: #666;
      line-height: 1.4;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }
  }
  
  .unread-dot {
    position: absolute;
    top: 30rpx;
    right: 30rpx;
    width: 16rpx;
    height: 16rpx;
    background: #ff4757;
    border-radius: 50%;
  }
}

.empty-state {
  padding: 80rpx 30rpx;
  text-align: center;
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

.loading-more {
  padding: 20rpx;
  text-align: center;
  font-size: 24rpx;
  color: #999;
}
</style>